package com.example.myapplication.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import com.example.myapplication.R;
import com.example.myapplication.fragment.HomeFragment;
import com.example.myapplication.fragment.MineFragment;
import com.example.myapplication.fragment.NewsFragment;
import com.example.myapplication.fragment.PostFragment;
import com.example.myapplication.fragment.ServiceFragment;
import com.google.android.material.tabs.TabLayout;

import java.util.List;

/**
 * @Author: Ng
 * @Date: 2024/4/8
 * @Versopn: 1.0.0
 * @Description: 标题栏切换
 */
public class MainTabAdapter extends FragmentPagerAdapter {

    private List<Fragment> fragments;
    private String[] titles;
    private Context context;
    private TabLayout tabLayout;
    private int[] selectIcon;
    private int[] unSelectIcon;

    public MainTabAdapter(@NonNull FragmentManager fm, List<Fragment> fragments, String[] titles, Context context, TabLayout tabLayout, int[] select, int[] unSelect) {
        super(fm);
        this.fragments = fragments;
        this.titles = titles;
        this.context = context;
        this.tabLayout = tabLayout;
        this.selectIcon = select;
        this.unSelectIcon = unSelect;
    }

    /**
     * 返回当前的 Fragment
     * @param position: 当前页面的位置
     */
    @NonNull
    @Override
    public Fragment getItem(int position) {
        if (position == 0) {
            return new HomeFragment();
        } else if (position == 1) {
            return new ServiceFragment();
        } else if (position == 2) {
            return new PostFragment();
        } else if (position == 3) {
            return new NewsFragment();
        } else if (position == 4) {
            return new MineFragment();
        }
        return new HomeFragment();
    }

    /**
     * Fragment 中的个数
     */
    @Override
    public int getCount() {
        return titles.length;
    }

    /**
     * 返回当前标题
     */
    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return titles[position];
    }

    public View getView(int position) {
        View view = LayoutInflater.from(context).inflate(R.layout.tab_item, null);
        ImageView imageView = view.findViewById(R.id.tab_item_icon);
        TextView textView = view.findViewById(R.id.tab_item_text);
        if (tabLayout.getTabAt(position).isSelected()) {
            imageView.setImageResource(selectIcon[position]);
        } else {
            imageView.setImageResource(unSelectIcon[position]);
        }
        textView.setText(titles[position]);
        textView.setTextColor(tabLayout.getTabTextColors());
        return view;
    }
}
